package com.web;

import com.bean.Post;
import com.dao.PostDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/post/list")
public class PostListServlet extends HttpServlet {
    /**
     * 查询所有信息一般用 doGet 方法
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建 postDao 对象
        PostDao postDao = new PostDao();

        try {
            // 实现查询所有信息方法
            List<Post> posts = postDao.getAll();
            // 把信息存到 posts 中处理
            req.setAttribute("posts", posts);

            // 页面转发主页面
            req.getRequestDispatcher("/post/posts.jsp").forward(req, resp);
        } catch (Exception e) {
            // 把异常打印到控制台
            e.printStackTrace();
            // 把信息存到 error 中处理
            req.setAttribute("error: " , e.getLocalizedMessage());
            // 页面转发
            req.getRequestDispatcher("/post/error.jsp").forward(req, resp);
        }
    }
}
